package edu.washington.ling.syntric.io;

import java.util.regex.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;


public class ExampleDocReaderSGML extends ExampleDocReader {
	
	
	private static Pattern exampleStartPattern = Pattern.compile("\\<Sentence id\\s*\\=\\s*[\"\']?([^.\"]+)(\\.ssf)?\\s*[\"\']?\\>");
	private static Pattern origPattern = Pattern.compile("<Original>(.+?)</Original>");
	private static Pattern glossPattern = Pattern.compile("<Gloss>(.+?)</Gloss>");
	private static Pattern transPattern = Pattern.compile("<Translation>(.+?)</Translation>");
	private static Pattern exampleEndPattern = Pattern.compile("\\<\\/Sentence\\>");
	
	
	protected ExampleDocReaderSGML(String path) {
		super(path);
	}
	
	@Override
	public ExampleDoc read() throws IOException {
		ExampleDoc exDoc = new ExampleDoc();
		BufferedReader br = new BufferedReader(new FileReader(new File(this.getPath())));
		Example ex = null;
		String line = null;
		while ((line = br.readLine()) != null) {
			Matcher mStart = exampleStartPattern.matcher(line);
			Matcher mEnd = exampleEndPattern.matcher(line);
			if (mStart.matches()) {
				String id = mStart.group(1);
				ex = new Example(id);
			}
			else if (trySetOriginal(line, ex)) { continue; }
			else if (trySetGloss(line, ex)) { continue; }
			else if (trySetTranslation(line, ex)) { continue; }
			else if (mEnd.matches()) {
				if (exDoc.hasExample(ex.getID())) {
					String errStr = String.format("Error: example '%s' has already been seen.\n", ex.getID());
					System.err.println(errStr);
				}
				else {
					exDoc.addExample(ex);
				}
			}
			
		}
		exDoc.resetIterator();
		return exDoc;
	}

	public boolean trySetOriginal(String line, Example exr) {
		Matcher m = origPattern.matcher(line);
		if (m.matches()) {
			exr.setOriginal(m.group(1));
			return true;
		}
		return false;
	}
	public boolean trySetGloss(String line, Example exr) {
		Matcher m = glossPattern.matcher(line);
		if (m.matches()) {
			exr.setGloss(m.group(1));
			return true;
		}
		return false;
	}
	public boolean trySetTranslation(String line, Example exr) {
		Matcher m = transPattern.matcher(line);
		if (m.matches()) {
			exr.setTranslation(m.group(1));
			return true;
		}
		return false;
	}
}
